#!/usr/bin/env python
#Echo Server with timeout

import socket, traceback

host = ''
port = 51423

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)

while True:
    try:
        clientsocket, clientaddr = s.accept()

    except KeyboardInterrupt:
        raise
    except:
        traceback.print_exc()
        continue

    clientsocket.settimeout(5)


    try:
        print "Got connection from ", clientsocket.getpeername()
        while True:
            data = clientsocket.recv(4096)
            if not len(data):
                break
            clientsocket.sendall(data)

    except (KeyboardInterrupt, SystemExit):
        raise
    except socket.timeout:
        pass
        print "timeout next close socket"
    except:
        traceback.print_exc()

    try:
        clientsocket.close()
    except KeyboardInterrupt:
        raise
    except:
        traceback.print_exc()


